# -*- coding:utf-8 -*-

import binascii
import hashlib
import hmac
import random
import requests
import json
import time
import base64
import xlwt
from datetime import datetime
from json_data import ai_users, case_list, users

pass    # todo ###########################################  跑数据  对战数据统计 多人多箱
loss_users = []
run_number = 1
while True:
    if len(users) == len(loss_users):
        break
    # 选择用户
    user = random.sample(users, 1)[0]
    if not user["state"]:
        continue

    # 选择箱子
    max_keys = random.randint(1, 2)
    create_box = random.sample(case_list, random.randint(1, max_keys))
    for i in range(random.randint(1, 2)):
        max_len = 3 if len(create_box) > 3 else len(create_box)
        join_result = random.sample(create_box, random.randint(1, max_len))
        create_box += join_result

    # 计算价格
    total_price = 0
    round_cases = []
    for b in create_box:
        if user["money"] > total_price:
            total_price += b["price"]
            round_cases.append(b)

    # 开始回合
    print("回合数", run_number, "当前用户", user["user"], "用户余额", user["money"], "箱子数量", len(round_cases), "箱子数量", len(round_cases))
    if len(round_cases) >= 1:
        user.update(money=round(user['money'] - total_price, 2))
        user_get = 0
        ai_get = 0
        for case in round_cases:
            # 开始用户跑箱子
            if user['round'] == 0:
                _ini_round = random.randint(0, 100000)
                user.update(round=_ini_round)
                user['round'] = _ini_round
            user_round = user['round'] + 1
            user.update(round=user_round)
            secret = binascii.unhexlify(user['hash'])
            seed = (user['seed'] + "-" + str(user_round)).encode("utf8")
            roll_hash = hmac.new(secret, seed, hashlib.sha512).hexdigest()
            subHash = roll_hash[:7]
            sixteen_int = int(subHash, 16)
            roll = sixteen_int % 1000000 + 1

            # 获取箱子饰品
            drops = case["drop"]
            item = {}
            for key in drops:
                roll_min_max = key.split("-")
                if int(roll_min_max[0]) < roll <= int(roll_min_max[1]):
                    item = drops[key]
                    break
            if item == {}:
                continue

            user_get += item["price"]

            # ai跑箱子
            if ai_users['round'] == 0:
                ai_users_ini_round = random.randint(0, 100000)
                ai_users.update(round=ai_users_ini_round)
                ai_users['round'] = ai_users_ini_round
            ai_user_round = ai_users['round'] + 1
            ai_users.update(round=ai_user_round)
            ai_secret = binascii.unhexlify(ai_users['hash'])
            ai_seed = (ai_users['seed'] + "-" + str(ai_user_round)).encode("utf8")
            ai_roll_hash = hmac.new(ai_secret, ai_seed, hashlib.sha512).hexdigest()
            ai_subHash = ai_roll_hash[:7]
            ai_sixteen_int = int(ai_subHash, 16)
            ai_roll = ai_sixteen_int % 1000000 + 1

            ai_drops = case["ai_drop"]
            ai_item = {}
            for ai_key in ai_drops:
                ai_roll_min_max = ai_key.split("-")
                if int(ai_roll_min_max[0]) < ai_roll <= int(ai_roll_min_max[1]):
                    ai_item = ai_drops[ai_key]
                    break
            if ai_item == {}:
                continue
            ai_get += ai_item["price"]
            print("{}回合".format(run_number), "箱子", case["name"], "用户：", user["user"], "用户开出：", user_get, "AI：", ai_get)

        # 判断输赢
        win_get = 0
        win = 0
        if user_get > ai_get:
            win_get = user_get + ai_get
            win = 1
        elif user_get == ai_get:
            win = 1
            win_get = user_get

        print("{}回合结果".format(run_number), "用户：", user["user"], "用户开出：", user_get, "AI：", ai_get, "输赢", win)

        user.update(cost=user['cost'] + total_price)
        user.update(get=user['get'] + win_get)
        user.update(run_round=(user['run_round'] if 'run_round' in user else 0) + 1)
        user.update(win_round=(user['win_round'] if 'win_round' in user else 0) + win)
        run_number += 1
    else:
        if user["money"] <= 5:
            user.update(state=False)
            loss_users.append(user)

table = xlwt.Workbook(encoding='utf-8')
style = xlwt.XFStyle()
alignment = xlwt.Alignment()
alignment.horz = 0x02
alignment.vert = 0x01
style.alignment = alignment

sheet1 = table.add_sheet("sheet1")
sheet1.write(0, 0, '用户', style)
sheet1.write(0, 1, '花费金额', style)
sheet1.write(0, 2, '赢的金额', style)
sheet1.write(0, 3, '总次数', style)
sheet1.write(0, 4, '赢次数', style)
sheet1.write(0, 6, '用户总花费', style)
sheet1.write(0, 7, '用户总获得', style)


total_cost = 0
total_get = 0
y = 1
for user in users:
    sheet1.write(y, 0, user["user"], style)
    sheet1.write(y, 1, round(user["cost"], 2), style)
    sheet1.write(y, 2, round(user["get"], 2), style)
    sheet1.write(y, 3, user["run_round"], style)
    sheet1.write(y, 4, user["win_round"], style)
    total_cost += user["cost"]
    total_get += user["get"]

    y += 1

sheet1.write(1, 6, round(total_cost, 2), style)
sheet1.write(1, 7, round(total_get, 2), style)

table.save("2022-12-3 用户对战数据.xls")


